package cn.swjtuhc.ss.hljapi.client;

import cn.dev33.satoken.stp.StpUtil;
import cn.swjtuhc.ss.hljapi.config.AliyunOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author: chenximeng
 * @date: 2024/5/10 16:46
 */

@Slf4j
@Component
public class AliyunOssClient {

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    /**
     * 阿里云OSS文件上传
     *
     * @param file 文件
     * @param prefix 文件夹路径 eg:travel/img/
     */
    public String upload(MultipartFile file, String prefix) {

        //获取相关配置
        String bucketName = aliyunOssConfig.getBucketName();
        String endPoint = aliyunOssConfig.getEndPoint();
        String accessKeyId = aliyunOssConfig.getAccessKeyId();
        String accessKeySecret = aliyunOssConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = generateTime();

        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = prefix + fileName + extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 获取随机字符串
     * @return
     */
    private String generateTime() {
        return String.valueOf(System.currentTimeMillis());
    }
}
